﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using PMPUtils.DB;
using PMPUtils.Form;
using PMPUtils.Documentation;
using PMPUtils.Resources;
using System.Net.Mail;

namespace PMP.Documentation
{
    public partial class KnowledgeBase : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FormUtil.Authenticate(Session, Response);

            if (!IsPostBack)
            {
                InitiateGridView();

                txtID.Text = String.Empty;
                lblMsg.Text = String.Empty;
            }
        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblMsg.Text = String.Empty;

            RefreshType();
        }

        private void InitiateGridView()
        {
            InitiateGridView(String.Empty);
        }

        private void InitiateGridView(String ID)
        {
            lblMsg.Text = String.Empty;
            txtID.Text = String.Empty;

            if (grvKnowledgeBase.Columns.Count == 0)
            {
                // Add column
                ButtonField details = new ButtonField();
                details.ButtonType = ButtonType.Link;
                details.CommandName = "details";
                details.Text = "details";

                BoundField type = new BoundField();
                type.HeaderText = "type";
                type.DataField = "type";

                BoundField title = new BoundField();
                title.HeaderText = "title";
                title.DataField = "title";

                BoundField issue = new BoundField();
                issue.HeaderText = "issue";
                issue.DataField = "issue";

                BoundField label = new BoundField();
                label.HeaderText = "label";
                label.DataField = "label";

                BoundField author = new BoundField();
                author.HeaderText = "author";
                author.DataField = "author";

                BoundField IDCol = new BoundField();
                IDCol.HeaderText = "ID";
                IDCol.DataField = "ID";

                grvKnowledgeBase.Columns.Add(details);
                grvKnowledgeBase.Columns.Add(type);
                grvKnowledgeBase.Columns.Add(title);
                grvKnowledgeBase.Columns.Add(issue);
                grvKnowledgeBase.Columns.Add(label);
                grvKnowledgeBase.Columns.Add(author);
                grvKnowledgeBase.Columns.Add(IDCol);

                // List Data
                DataTable dtKnowledgeBase = new DataTable();
                try
                {
                    String strKnowledgeBase = "SELECT [type], [title], [issue], [resolution], [label], usr.usr_name [author], knowledgebase.ID FROM [KnowledgeBase] join usr on (usr.id = KnowledgeBase.author) where 1 = 2";
                    if (!ID.Equals(String.Empty))
                    {
                        strKnowledgeBase += " where knowledgebase.id = " + ID;
                    }
                    strKnowledgeBase += " ORDER BY [type], [title]";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    dtKnowledgeBase = localOperator.Read(strKnowledgeBase);
                }
                catch (Exception ex)
                {
                    lblMsg.Text = ex.Message;
                    return;
                }

                grvKnowledgeBase.DataSource = dtKnowledgeBase.DefaultView;
                grvKnowledgeBase.DataBind();
            }
        }

        protected void grvKnowledgeBase_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            txtID.Text = String.Empty;
            lblMsg.Text = String.Empty;

            // Convert the row index stored in the CommandArgument
            // property to an Integer.
            int index = Convert.ToInt32(e.CommandArgument);

            // Retrieve the row that contains the button clicked 
            // by the user from the Rows collection.
            GridViewRow row = grvKnowledgeBase.Rows[index];

            String ID = GridViewOperator.GetCellStringValue(grvKnowledgeBase, row, "ID");
            String author = GridViewOperator.GetCellStringValue(grvKnowledgeBase, row, "author");
            String type = GridViewOperator.GetCellStringValue(grvKnowledgeBase, row, "type");
            String title = GridViewOperator.GetCellStringValue(grvKnowledgeBase, row, "title");
            String label = GridViewOperator.GetCellStringValue(grvKnowledgeBase, row, "label");
            String issue = GridViewOperator.GetCellStringValue(grvKnowledgeBase, row, "issue");

            if (e.CommandName.Equals("details"))
            {
                RefreshType(type);

                txtID.Text = ID;
                ddlAuthors.SelectedItem.Text = author;
                ddlType.SelectedValue = type;
                txtLabel.Text = label.Replace('\"', '\'');
                txtTitle.Text = title.Replace('\"', '\'');
                txtIssue.Text = issue.Replace('\"', '\'');

                try
                {
                    String resolution = ReadResolution(ID);
                    ftbResolution.Text = resolution;
                }
                catch (Exception ex)
                {
                    lblMsg.Text = ex.Message;
                    return;
                }
            }
        }

        private String ReadResolution(String ID)
        {
            DataTable dtResolution = new DataTable();
            String strQueryResolution = "select resolution from knowledgebase where ID = " + ID;
            DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
            dtResolution = localOperator.Read(strQueryResolution);

            foreach (DataRow row in dtResolution.Rows)
            {
                if (row["resolution"] != null)
                {
                    String resolution = row["resolution"].ToString().Trim();
                    return resolution.Replace('\"', '\'');
                }
            }

            return String.Empty;
        }

        private void RefreshType()
        {
            RefreshType(String.Empty);
        }

        private void RefreshType(String type)
        {
            if (type.Equals(String.Empty))
            {
                type = ddlType.SelectedValue;
            }

            if (type.Equals("Issue"))
            {
                txtIssue.Text = String.Empty;

                lblIssue.Visible = true;
                txtIssue.Visible = true;
            }
            else
            {
                txtIssue.Text = String.Empty;

                lblIssue.Visible = false;
                txtIssue.Visible = false;
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (ddlAuthors.SelectedIndex == -1 ||
                ddlType.SelectedIndex == -1 ||
                txtLabel.Text.Equals(String.Empty) ||
                txtTitle.Text.Equals(String.Empty) ||
                ftbResolution.Text.Equals(String.Empty))
            {
                lblMsg.Text = "Please fill required fields!";
                return;
            }

            if (ddlType.SelectedValue.Equals("Issue") &&
                txtIssue.Text.Equals(String.Empty))
            {
                lblMsg.Text = "Please fill the issue description!";
                return;
            }


            if (txtTitle.Text.Contains('\'') || txtTitle.Text.Contains('\"'))
            {
                lblMsg.Text = "Title Should Not Contain Either ' or \"!";
                return;
            }

            if (txtIssue.Text.Contains('\'') || txtIssue.Text.Contains('\"'))
            {
                lblMsg.Text = "Issue Should Not Contain Either ' or \"!";
                return;
            }

            String author = ddlAuthors.SelectedValue.Trim();
            String type = ddlType.SelectedValue.Trim();
            String label = txtLabel.Text.Trim();

            String title = txtTitle.Text.Trim();
            title = title.Replace('\'', '\"');

            String issue = txtIssue.Text.Trim();
            issue = issue.Replace('\'', '\"');

            String resolution = ftbResolution.Text.Trim();
            resolution = resolution.Replace('\'', '\"');

            if (txtID.Text.Trim().Equals(String.Empty))
            {
                try
                {
                    String strInsert = "insert into KnowledgeBase (type, title, issue, resolution, label, author) values " +
                        " ('" + type + "', '" + title + "', '" + issue + "', '" + resolution + "', '" + label + "', " + author + ")";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsert);
                }
                catch (Exception ex)
                {
                    lblMsg.Text = ex.Message;
                    return;
                }
            }
            else
            {
                try
                {
                    String ID = txtID.Text.Trim();

                    String strUpdate = "update KnowledgeBase set " +
                        " type = '" + type + "'" +
                        ", title = '" + title + "'" +
                        ", issue = '" + issue + "'" +
                        ", resolution = '" + resolution + "'" +
                        ", label = '" + label + "'" +
                        ", author = " + author + "" +
                        " where id = " + ID; 
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strUpdate);
                }
                catch (Exception ex)
                {
                    lblMsg.Text = ex.Message;
                    return;
                }
            }

            MailAddress senderMailAddress = ResourceOperator.GetEmailAddress(ddlAuthors.SelectedItem.Text.Trim());
            DocumentOperator.SendKnowledgeBaseUpdate(senderMailAddress, title);

            // Initialize the view
            InitiateGridView();
            Search();

            txtID.Text = String.Empty;
            lblMsg.Text = String.Empty;

            Clean();
        }

        protected void btnSeach_Click(object sender, EventArgs e)
        {
            if (txtTitle.Text.Contains('\'') || txtTitle.Text.Contains('\"'))
            {
                lblMsg.Text = "Title Should Not Contain Either ' or \"!";
                return;
            }

            if (txtIssue.Text.Contains('\'') || txtIssue.Text.Contains('\"'))
            {
                lblMsg.Text = "Issue Should Not Contain Either ' or \"!";
                return;
            }

            Search();
        }

        private void Search()
        {
            txtID.Text = String.Empty;
            lblMsg.Text = String.Empty;

            InitiateGridView();

            String author = ddlAuthors.SelectedValue.Trim();
            String type = ddlType.SelectedValue.Trim();
            String[] labelKeys = txtLabel.Text.Trim().Split(' ');
            String[] titleKeys = txtTitle.Text.Trim().Split(' ');
            String[] issueKeys = txtIssue.Text.Trim().Split(' ');

            String criteria = " where 1 = 1 ";

            if (!author.Equals(String.Empty) && !author.Equals("0")) { criteria += " and author = " + author + ""; }
            if (!type.Equals(String.Empty)) { criteria += " and type = '" + type + "'"; }

            // Process Labels
            if (!txtLabel.Text.Trim().Equals(String.Empty)) { criteria += " and ("; }
            bool likeAdded = false;
            for (int i = 0; i < labelKeys.Length; i++)
            {
                if (!likeAdded)
                {
                    if (!labelKeys[i].ToString().Trim().Equals(String.Empty))
                    {
                        criteria += " label like '%" + labelKeys[i] + "%'";
                        likeAdded = true;
                    }
                }
                else
                {
                    if (!labelKeys[i].ToString().Trim().Equals(String.Empty))
                    {
                        criteria += " or label like '%" + labelKeys[i] + "%'";
                    }
                }
            }
            if (likeAdded) { criteria += " )"; }

            // Process Titles
            String criteriaFull = criteria;
            String criteriaLike = criteria;
            if (!txtTitle.Text.Trim().Equals(String.Empty)) {
                criteriaFull += " and ( title like '%" + txtTitle.Text.Trim() + "%' )";
                criteriaLike += " and (";
            }
            likeAdded = false;
            for (int i = 0; i < titleKeys.Length; i++)
            {
                if (!likeAdded)
                {
                    if (!titleKeys[i].ToString().Trim().Equals(String.Empty))
                    {
                        criteriaLike += " title like '%" + titleKeys[i] + "%'";
                        likeAdded = true;
                    }
                }
                else
                {
                    if (!titleKeys[i].ToString().Trim().Equals(String.Empty))
                    {
                        criteriaLike += " or title like '%" + titleKeys[i] + "%'";
                    }
                }
            }
            if (likeAdded) { criteriaLike += " )"; }

            // Process Issues
            if (!txtIssue.Text.Trim().Equals(String.Empty)) {
                criteriaFull += " and ( issue like '%" + txtIssue.Text.Trim() + "%' )";
                criteriaLike += " and (";
            }
            likeAdded = false;
            for (int i = 0; i < issueKeys.Length; i++)
            {
                if (!likeAdded)
                {
                    if (!issueKeys[i].ToString().Trim().Equals(String.Empty))
                    {
                        criteriaLike += " issue like '%" + issueKeys[i] + "%'";
                        likeAdded = true;
                    }
                }
                else
                {
                    if (!issueKeys[i].ToString().Trim().Equals(String.Empty))
                    {
                        criteriaLike += " or issue like '%" + issueKeys[i] + "%'";
                    }
                }
            }
            if (likeAdded) { criteriaLike += " )"; }

            // List Data
            String strKnowledgeBase = "SELECT [type], [title], [issue], [resolution], [label], usr.usr_name [author], knowledgebase.ID FROM [KnowledgeBase] join usr on (usr.id = KnowledgeBase.author)" +
                " " + criteriaFull +
                " union all " +
                "SELECT [type], [title], [issue], [resolution], [label], usr.usr_name [author], knowledgebase.ID FROM [KnowledgeBase] join usr on (usr.id = KnowledgeBase.author)" +
                " " + criteriaLike + " and title not in (SELECT [title] FROM [KnowledgeBase] join usr on (usr.id = KnowledgeBase.author)" + criteriaFull + ")";
            DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
            DataTable dtKnowledgeBase = localOperator.Read(strKnowledgeBase);

            grvKnowledgeBase.DataSource = dtKnowledgeBase.DefaultView;
            grvKnowledgeBase.DataBind();
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            Clean();
        }

        private void Clean()
        {
            ddlAuthors.ClearSelection();
            ddlType.SelectedIndex = -1;
            txtLabel.Text = String.Empty;
            txtTitle.Text = String.Empty;
            txtIssue.Text = String.Empty;
            ftbResolution.Text = String.Empty;
        }

        protected void txtTitle_TextChanged(object sender, EventArgs e)
        {
            //String userName = FormUtil.GetSessionUserName(Session);
            //foreach (ListItem item in ddlAuthors.Items)
            //{
            //    if (item.Text.Equals(userName.Trim()))
            //    {
            //        ddlAuthors.ClearSelection();
            //        item.Selected = true;
            //        break;
            //    }
            //}
        }
    }
}
